package Sort;

public class QuickSort {
    /**
     * 快速排序
     */

    public static void swap(int[] arr,int i,int j){
        int tem=arr[i];
        arr[i]=arr[j];
        arr[j]=tem;
    }
    public static void quickSort(int[] arr,int start,int end){
        if(start>=end){
            return;
        }
        int midVal=getMiddleNumber(arr,start,end);
        swap(arr,start,midVal);
        int pivot=partition1(arr,start,end);

        quickSort(arr,start,pivot-1);
        quickSort(arr,pivot+1,end);

    }
    //hoare法
    public static int partition1(int[] arr,int left,int right){
        int par=arr[left];
        int tmp=left;
        while (left<right){
            while (left<right&&arr[right]>=par){
                right--;
            }
            while (left<right&&arr[left]<=par){
                left++;
            }
            swap(arr,left,right);
        }
        swap(arr,left,tmp);
        return left;
    }
    //挖坑法
    public static int partition2(int[] arr,int left,int right){
        int tmp=arr[left];
        while (left<right){
            while (left<right&&arr[right]>=tmp){
                right--;
            }
            arr[left]=arr[right];
            while (left<right&&arr[left]<=tmp){
                left++;
            }
            arr[right]=arr[left];
        }
        arr[right]=tmp;
        return right;
    }
    //前后指针法
    public static int partition3(int[] arr,int left,int right){
        int prev=left;
        int cur=left+1;
        while (cur<=right){
            if(arr[cur]<arr[left]&&arr[++prev]!=arr[cur]){
                swap(arr,prev,cur);
            }
            cur++;
        }
        swap(arr,prev,left);
        return prev;
    }

    //快速排序的优化(三数取中法)
    public static int getMiddleNumber(int[] arr,int left,int right){
        int mid=(left+right)/2;
        if(arr[left]<arr[right]){
            if(arr[mid]<arr[left]){
                return left;
            }else if(arr[mid]>arr[right]){
                return right;
            }else {
                return mid;
            }
        }else {
            if(arr[mid]>arr[left]){
                return left;
            }else if(arr[mid]<arr[right]){
                return right;
            }else {
                return mid;
            }
        }
    }
    public static void main(String[] args) {
        int[] array={5,1,9,4,3};
        quickSort(array,0,array.length-1);
        for (int i = 0; i <array.length; i++) {
            System.out.print(array[i]+" ");
        }
    }
}
